package com.quanbu.plugin;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.springframework.stereotype.Component;

import java.sql.Statement;
import java.util.Properties;

/**
 * 统计sql执行耗时
 * <br>CreateDate 2022-01-08 14:45
 *
 * @author yanghouhua
 * @since 1.0.0
 */
@Component
@Slf4j
@Intercepts(
        {
                @Signature(type=StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}),
                @Signature(type=StatementHandler.class, method = "update", args = {Statement.class}),
                @Signature(type=StatementHandler.class, method = "batch", args = {Statement.class})
        }
)
public class CountSqlTimeInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 开始时间
        long start = System.currentTimeMillis();

        // 获取Jdbc封装的StatementHandler
        Object target = invocation.getTarget();
        StatementHandler statementHandler = (StatementHandler)target;

        // 执行
        try {
            return invocation.proceed();
        } finally {
            long end = System.currentTimeMillis();
            BoundSql boundSql = statementHandler.getBoundSql();
            String sql = boundSql.getSql();
            log.info("执行SQL:{},共耗时：{}毫秒.", sql, (end - start));
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
            log.info("插件配置信息{}", properties);
    }
}
